/* (C) 2007-2009 caitong Limited
 * (C) 2009-2012  limited
 *
 * Authors:
 * legs.ant.king@gmail.com


   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include "../include/iInitPort.h"
#include "../include/InitVariable.h"
#include "../include/SentMsg.h"
#include "../include/Conn.h"
//#include <windows.h>
#include "/usr/include/mysql/mysql.h"
//#include "D:\Program Files\MySQL\MySQL Server 5.1\include\mysql.h"
using namespace std;

char * getnow(char *now, int size, char *fmt);



void Conncect(char iPortList[][10],char iArgument[][50],char iCompasion[][50])
{
	cout<<endl;
	int portcount=iInitPortValue(iPortList,iArgument,iCompasion);
	int UserName=GetMatachChar(iCompasion,"user");
	int Password=GetMatachChar(iCompasion,"password");
	int DataBase=GetMatachChar(iCompasion,"dbname");
	int Hostname=GetMatachChar(iCompasion,"hostname");
	int ErrSentPerfd=GetMatachChar(iCompasion,"errsentperf");
	int WarSentperfd=GetMatachChar(iCompasion,"warsentperf");
	int SleepTimed=GetMatachChar(iCompasion,"sleeptime");
	int MaxWarningValued=GetMatachChar(iCompasion,"MaxWarningValue");
	int iSentCount=GetMatachChar(iCompasion,"sentcount"); //Count Sent 
	int programsleepd=GetMatachChar(iCompasion,"programsleep");
	int sentmsgcnt=GetMatachChar(iCompasion,"sentmsg");	
	int sendmsgcnt=GetMatachChar(iCompasion,"sendto");
	
	int send_cn_email=atoi(iArgument[sendmsgcnt]);
	int programsleep=atoi(iArgument[programsleepd]);
	int MaxWarningValue=atoi(iArgument[MaxWarningValued]);//Ø®Â´ó¶¾Â¯Â¸ç¤Â±á©nt SleepTime=atoi(iArgument[SleepTime]);		//Â³Íóà Â±Â¼â¯s
	int ErrSentPerf=atoi(iArgument[ErrSentPerfd]);		//while Error,sent diff.	int WarSentperf=atoi(iArgument[WarSentperfd]);
	int WarSentperf=atoi(iArgument[WarSentperfd]);
	int sentmsgvat=atoi(iArgument[sentmsgcnt]);
	int SleepTime=atoi(iArgument[SleepTimed]);
	int SentCount=atoi(iArgument[iSentCount]);
	
	int WarningNum=0; //Warning num
	int ErrorNum=0;	 	//Error num
	int sendnum=0;
	int SentNum=0; //add performent num
	char now[20]={0};
	char nowtime[20]={0};
	int SleepTenMuitil=600;
	sprintf(nowtime,"%s",getnow(now,sizeof(now), "%Y.%m.%d %H:%M:%S"));
	unsigned int res; //res ptr

	int LogFile=GetMatachChar(iCompasion,"logfile");
	cout<<"Log to : "<<iArgument[LogFile]<<"\n\n";
	if(sentmsgvat == 1)
	{
		printf("can't Sent message in Mode running .\n");
	}
	if(send_cn_email == 1)
	{
		cout<<"Can't Send Email in Mode Running .\n";
		cout<<send_cn_email<<endl;
	}

	bool prostatus=1;	//program status 0 = sleep 1 = working
	MYSQL Conn;
	MYSQL_RES *res_ptr;
	MYSQL_ROW sqlrow;
	mysql_init(&Conn);
	
	while(1)
	{
		cout<<"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"<<endl;
		for(int i=0;i<portcount;i++)
		{
			if(mysql_real_connect(&Conn,iArgument[Hostname],iArgument[UserName],iArgument[Password],iArgument[DataBase],atoi(iPortList[i]),NULL,0))
			{
				cout<<"Local host port is : \t\t"<<atoi(iPortList[i])<<endl;
				res=mysql_query(&Conn,"show slave status");
				//cout<<res<<endl;
				if(res)
				{
					cout<<"Select Error : "<<mysql_error(&Conn)<<"\n";
				}
				else
				{
					cout<<"dateTime   is : "<<nowtime<<endl;
					cout<<"Connect to Server Successful."<<endl;
					res_ptr=mysql_store_result(&Conn);
					if(res_ptr)
					{
						while((sqlrow=mysql_fetch_row(res_ptr)))
						{
							if((unsigned long)mysql_num_rows(res_ptr)<1)
							{
								cout<<(unsigned long)mysql_num_rows(res_ptr)<<endl;
								cout<<"Mysql Replication not running . Local Port is"<<iPortList[i]<<endl;
								continue;
							}
							else
							{
								cout<<"Remote Server Port  is : "<<sqlrow[3]<<endl;
								cout<<"Remote Hostname     is : "<<sqlrow[1]<<endl;
								cout<<"Retrieved Rows				: "<<(unsigned long)mysql_num_rows(res_ptr)<<endl;
								unsigned int column_count=mysql_field_count(&Conn);
								cout<<"This select Count columns		: "<<column_count<<endl;
								cout<<"Slave IO  Status is			: "<<sqlrow[10]<<endl;
								cout<<"Slave SQL Status is			: "<<sqlrow[11]<<endl;
								if(sqlrow[32]==NULL)
									cout<<"Slave Replication Value is	NULL"<<endl;
								else
									cout<<"Slave Replication Value is		: "<<sqlrow[32]<<endl;

								char IONotWork[180]={0};
								sprintf(IONotWork,"%s Replication Error host %s io process not work",nowtime,sqlrow[1]);
								char *IONotWorkChat="Error : Replication IO not work .";
							//	cout<<IONotWork<<endl<<IONotWorkChat<<endl;

								//SentMsg(IONotWork,iCompasion,iArgument);
	
								char SQLNotWork[180]={0};
								sprintf(SQLNotWork,"%s Replication Error host %s SQL process not work",nowtime,sqlrow[1]);
								char *SQLNotWorkChat="Error : Replication SQL not work .";
							//	cout<<SQLNotWork<<endl<<SQLNotWorkChat<<endl;

								char RepValueNull[180]={0};
								sprintf(RepValueNull,"%s Warning Replication host %s repliaction error seconds is Null",nowtime,sqlrow[1]);
								char *RepValueNullChat="Warning : Replication values is : Null\nplease wait send in note . . .\n";
							//	cout<<RepValueNull<<endl<<RepValueNullChat<<endl;

								char RepValueMax[180]={0};
								sprintf(RepValueMax,"%s Warning replication host %s repliaction than %d vaues is : %d",nowtime,sqlrow[1],sqlrow[32],MaxWarningValue);
								char *RepValueMaxChat="Warning : Replication than MaxWarningValue seconds values\n";
							//	cout<<RepValueMax<<endl<<RepValueMaxChat<<endl;

								if(strcmp(sqlrow[10],"Yes") == 0)
								{
									cout<<"Slave IO  process is Normal work\tOK\n";
								}
								else
								{
									cout<<IONotWorkChat<<endl;
									WriteLog(iArgument,iCompasion,IONotWork);
									ErrorNum++;
									if(ErrorNum>ErrSentPerf) //Â´î³Â·Â¢ÊºÂµÄ´Î`									
									{
										if(SentNum<SentCount) //Â·Â¢ÌÑÏ¢ÂµÄ´Ïï½?				
										{
												cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
											cout<<"Please waiting send in Msg ..........";
											cout<<endl;
											if(sentmsgvat == 0)
											{
											SentMsg(IONotWork,iCompasion,iArgument);
											SentNum++;
											}
											if(send_cn_email == 0)
											{
											sendtomsg(IONotWork,iCompasion,iArgument);
												sendnum++;
											}
											ErrorNum=0;	//Â·Â¢ÌÑÏ¢Âºó±¤Â¤ÕÂ¹Ì¶Â¨Â´Ïï¿½ÔÂ·Â¢ÌÑÂ·Þ¼Çï¿½Â
											break;
										}
										else
										{
												break;
												prostatus=0;  //program in sleep status
										}
									}
								}
								if(strcmp(sqlrow[11],"Yes")==0)
								{
									cout<<"Slave SQL process is Normal work\tOK\n";
								}
								else
								{
									cout<<SQLNotWorkChat<<endl;
									WriteLog(iArgument,iCompasion,SQLNotWork);
									ErrorNum++;
									if(ErrorNum>=ErrSentPerf)	//Â´î³Â·Â¢ÊºÂµÄ´Î`									
									{
										if(SentNum<SentCount)	//Â·Â¢ÌÑÏ¢ÂµÄ´Ïï½?				
										{
											cout<<"Please waiting send in note .........";
											cout<<endl;
											if(sentmsgvat == 0)
                      {
												SentMsg(SQLNotWork,iCompasion,iArgument);
												SentNum++;	//Â·Â¢ÌÂ¼Çï½?							ErrorNum=0;	//Â·Â¢ÌÑÏ¢Âºó±¤Â¤ÕÂ¹Ì¶Â¨Â´Ïï¿½ÔÂ·Â¢ÌÑÂ·Þ¼Çï¿½Â										
											}
											if(send_cn_email == 0)
											{
												sendtomsg(IONotWork,iCompasion,iArgument);
												sendnum++;
											}
											break;
										}
										else
										{
											break;
											prostatus=0;  //program in sleep status
										}
									}
									
								}
								if (sqlrow[32] == NULL)
								{
									cout<<RepValueNullChat;
									WriteLog(iArgument,iCompasion,RepValueNull);
									WarningNum++;
									if(WarningNum<WarSentperf) //Â¾Â¯Â¸æ·¢ÊºÂµÄ´Î`									
									{
										if(SentNum<SentCount)
										{
											cout<<"Please waiting send in note..........\n";
											//cout<<RepValueNull<<" : "<<iCompasion<<" : "<<iArgument<<endl;
											if(sentmsgvat == 0)
                      {
												SentMsg(RepValueNull,iCompasion,iArgument);
												SentNum++;
											}
											if(send_cn_email == 0)
											{
												sendtomsg(IONotWork,iCompasion,iArgument);
												sendnum++;
											}
											ErrorNum=0;
											break;
										}
										else
										{
											break;
											prostatus=0;  //program in sleep status
										}
									}
								}
								else
								{
									if(atoi(sqlrow[32])<MaxWarningValue)
										cout<<"Replication Less "<<MaxWarningValue<<"\t\t\tOK"<<endl;
									else
									{
										cout<<RepValueMaxChat<<endl;
										WriteLog(iArgument,iCompasion,RepValueMax);
										WarningNum++;
										if(WarningNum>=WarSentperf)
										{
											if(SentNum<SentCount)
											{
												cout<<"Please waiting send in note .........";
												cout<<endl;
												if(sentmsgvat == 0)
                        {
													SentMsg(RepValueMax,iCompasion,iArgument);
													SentNum++;
												}
												if(send_cn_email == 0)
												{
													sendtomsg(IONotWork,iCompasion,iArgument);
													sendnum++;
												}
												WarningNum=0;
												break;
											}
											else
											{
												break;
												prostatus=0;  //program in sleep status
											}
										}
									}
								}
							}
						}
						if(mysql_errno(&Conn))
						{
							printf("Rerieved Error\n Error id: %d \n Error info :%s\n",mysql_error(&Conn),mysql_error(&Conn));
						}
					}
					mysql_free_result(res_ptr);
				}
				mysql_close(&Conn);
			}
			else
			{
				char errorid[100]={0};
				sprintf(errorid,"%s Connect to server Error in port: %s",nowtime,iPortList[i]);
				cout<<errorid<<"\t"<<iPortList[i]<<endl;
				WriteLog(iArgument,iCompasion,errorid);
				char errormsg[100]={0};
				sprintf(errormsg,"%s Connect to Server Failed \n, Error Msg : %s\n",nowtime,mysql_error(&Conn));
				cout<<errormsg<<endl;
				WriteLog(iArgument,iCompasion,errormsg);
			}
			printf ("\n###########################################################################\n\n");
			sleep(1);
		}
		if(prostatus==0)
		{
			sleep(programsleep);
			SentNum=0;
		}
		else
			sleep(SleepTime);
		programsleep=1;
		cout<<"Check Successful . program sleep "<<programsleep<<"time again try Check ...\n\n";
		
	}
	
}

char *getnow(char *now, int size, char *fmt)
{
        time_t  t;
        struct tm *pt;
        time(&t);
        pt = localtime(&t);
        strftime(now, size, fmt, pt);
        return now;
}



int WriteLog(char iArgument[][50],char iCompasion[][50],char *Context)
{
	int LogFile=GetMatachChar(iCompasion,"logfile");
	fstream logfile(iArgument[LogFile],ios::out | ios::app);
	logfile<<Context<<"\n";
	logfile.close();
return 1;
}





